package com.xaicode.template.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author Locker
 * @date 2021/8/4 0004 11:11
 */
@Component
@Slf4j
public class AsyncTask {

    @Async
    public void noReturn() {
        log.info("AsyncTask#noReturn {} start", Thread.currentThread().getName());
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("AsyncTask#noReturn {} end", Thread.currentThread().getName());
    }

    @Async
    public Future<String> hasReturn(int i) {
        log.info("AsyncTask#hasReturn {} with parameter i={} start", Thread.currentThread().getName(), i);
        Future<String> future;
        try {
            TimeUnit.SECONDS.sleep(i);
            future = new AsyncResult<>("success:" + i);
        } catch (InterruptedException e) {
            future = new AsyncResult<>("error");
        }
        return future;
    }

}
